export default class extends React.Component {
  constructor(props) {
    super(props);
    // 构造函数是唯一可以给 this.state 赋值的地方
    this.state = {
      msg: "Hello World",
      count: 1000,
      list: [],
      num: 2000,
    };
  }

  componentDidMount() {
    new Promise((resolve) => {
      setTimeout(() => {
        resolve("hello gp8");
      }, 1000);
    }).then((msg) => {
      console.log("--1", this.state.msg);
      this.setState({ msg }, () => console.log("--2", this.state.msg));
      console.log("--3", this.state.msg);
    });
  }

  hello() {
    console.log("--1", this.state.msg);
    this.setState(
      { msg: "See you again" },
      () => console.log("--3", this.state.msg),
      console.log("--2", this.state.msg)
    );
  }

  add() {
    console.log("---1", this.state.count);
    this.setState(
      (state) => ({
        count: state.count + 1,
      }),
      () => console.log("--3", this.state.count)
    );
    console.log("--2", this.state.count);
  }

  asyncAdd() {
    setTimeout(() => {
      console.log("--1", this.state.num);
      this.setState(
        (state) => ({
          num: state.num + 1,
        }),
        () => console.log("--2", this.state.num)
      );
      this.setState({ msg: "Hello GP8" }, () =>
        console.log("----3", this.state.num)
      );
      console.log("--3", this.state.num);
    }, 2000);
  }

  combine() {
    console.log("---1");
    this.setState(
      {
        msg: "hello gp9",
      },
      () => console.log("---end state", this.state)
    );
    console.log("---2");
    this.setState({
      msg: "Hello GP10",
      count: 3000,
      list: [1, 2],
    });
    console.log("---3");
    this.setState((state) => ({
      num: 4000,
      count: 5000,
      list: [3, 4],
    }));
    console.log("---4");
  }

  render() {
    const { msg, count, num } = this.state;
    return (
      <div>
        <h2>学习state</h2>
        <h2>{msg}</h2>
        <button onClick={() => this.hello()}>你好</button>
        <h2> {count}</h2>
        <button onClick={() => this.add()}>点击增加</button>
        <h2> {num}</h2>
        <button onClick={() => this.asyncAdd()}>异步增加</button>
        <hr />
        <button onClick={() => this.combine()}>合并</button>
      </div>
    );
  }
}
